package com.sfx.concurrent.demo.concurrent.ReentrantLock.condition;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.TestCondition")
public class TestCondition {
    private static boolean isCigarette = false;
    private static boolean isTakeOut = false;
    //每一个人不用去同一间休息室等了,而是去不同的休息室等待,这样就避免了通一间休息室全部唤醒的问题->虚假唤醒
    private static ReentrantLock ROOM = new ReentrantLock();//一个大房间有多间休息室
    private static Condition cigaretteWaitSet = ROOM.newCondition();
    private static Condition takeOutWaitSet = ROOM.newCondition();

    public static void main(String[] args) throws InterruptedException {
        //小南等烟
        new Thread(()->{
            ROOM.lock();
            try{
                log.debug("是否有香烟 : " +isCigarette);
                if(!isCigarette){
                    log.debug("没有香烟,干不了活,等一会");
                    try {
                        cigaretteWaitSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("小南开始干活");
            }finally {
                ROOM.unlock();
            }
        },"小南").start();

        //小女等外卖
        new Thread(()->{
            ROOM.lock();
            try{
                log.debug("是否有外卖 : " +isTakeOut);
                if(!isTakeOut){
                    log.debug("没有外卖,干不了活,等一会");
                    try {
                        takeOutWaitSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("小女干活");
            }finally {
                ROOM.unlock();
            }
        },"小女").start();

        Thread.sleep(1000);
        new Thread(()->{
            ROOM.lock();
            try {
                isTakeOut = true;
                log.debug("外卖到了");
                takeOutWaitSet.signal();
            }finally {
                ROOM.unlock();
            }
        },"送外卖的").start();
        Thread.sleep(1000);
        new Thread(()->{
            ROOM.lock();
            try {
                isCigarette = true;
                log.debug("烟到了");
                cigaretteWaitSet.signal();
            }finally {
                ROOM.unlock();
            }
        },"送烟的").start();
    }
}